const alarmRecordService = require("../services/alarmRecordServices");

class AlarmRecordController {
  /**
   * 构造函数，绑定所有方法到类的实例
   */
  constructor() {
    // 显式地将所有方法绑定到类的实例
    this.getAllAlarmRecords = this.getAllAlarmRecords.bind(this);
    this.getAlarmRecordById = this.getAlarmRecordById.bind(this);
    this.createAlarmRecord = this.createAlarmRecord.bind(this);
    this.updateAlarmRecord = this.updateAlarmRecord.bind(this);
    this.delAlarmRecordById = this.delAlarmRecordById.bind(this);
  }

  // handleRequest 必须为箭头函数
  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req);
      if (result.code === 0) {
        res.status(successStatus).json(result); // 成功
      } else {
        res.status(result.statusCode || 400).json(result); // 失败
      }
    } catch (error) {
      res.status(500).json({
        code: 1,
        msg: "服务器内部错误",
      });
    }
  };

  async getAllAlarmRecords(req, res) {
    await this.handleRequest(
      () => alarmRecordService.getAllAlarmRecords(),
      req,
      res
    );
  }

  async getAlarmRecordById(req, res) {
    await this.handleRequest(
      () => alarmRecordService.getAlarmRecordById(req.params.id),
      req,
      res
    );
  }

  async createAlarmRecord(req, res) {
    await this.handleRequest(
      () => alarmRecordService.createAlarmRecord(req.body),
      req,
      res,
      201 // 成功时返回 201
    );
  }

  async updateAlarmRecord(req, res) {
    await this.handleRequest(
      () => alarmRecordService.updateAlarmRecord(req.params.id, req.body),
      req,
      res
    );
  }

  async delAlarmRecordById(req, res) {
    await this.handleRequest(
      () => alarmRecordService.delAlarmRecordById(req.params.id),
      req,
      res,
      200
    );
  }
}

module.exports = new AlarmRecordController();
